package org.jinion.result.table;

import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;

import org.jinion.constants.DataTypeEnum;
import org.jinion.exception.JinionException;
import org.jinion.log.message.result.table.DefaultTableMessage;

/**
 * @author zhlmmc
 *
 */
public class DefaultTable extends AbstractTable {

	public DefaultTable(ResultSet resultSet) throws JinionException{
		super(resultSet);
	}
	@Override
	protected void buildTable() throws JinionException{
		//check the status of result set
		if(this.resultSet == null){
			throw new JinionException(DefaultTableMessage.M1.getMessageContent());
		} else{
			try {
				if(resultSet.getStatement().getConnection().isClosed()){
					throw new JinionException(DefaultTableMessage.M2.getMessageContent());
				}
				//build table, setup colums
				ResultSetMetaData rsmd = resultSet.getMetaData();
				int columnCount = rsmd.getColumnCount();
				for (int i = 1; i <= columnCount; i++) {
					TableColumn column = new TableColumn(this, i);
					column.setAutoIncrement(rsmd.isAutoIncrement(i));
					column.setColumnLable(rsmd.getColumnLabel(i));
					column.setColumnName(rsmd.getColumnName(i));
					if (rsmd.isNullable(i) == ResultSetMetaData.columnNoNulls) {
						column.setNullable(false);
					} else{
						column.setNullable(true);
					}
					column.setTableName(rsmd.getTableName(i));
					column.setDataType(DataTypeEnum.matchDataType(rsmd.getColumnType(i)));
					this.columns.add(column);
				}
				//fill rows
				this.resultSet.beforeFirst();
				int rowIndex = 0;
				while (resultSet.next()) {
					rowIndex++;
					TableRow row = new TableRow(this, rowIndex);
					for (int i = 1; i <= columnCount; i++) {
						row.setValue(i, resultSet.getObject(i));
					}
					rows.add(row);
				}
				//reset ResultSet
				resultSet.beforeFirst();
			} catch (SQLException e) {
				throw new JinionException(e);
			}
		}
	}
}
